package com.gnerv.battle.boot.framework.core.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @author Gnerv LiGen
 */
@Slf4j
@Component
@AllArgsConstructor
public class AsyncHandlerInterceptorChain {

    private final List<AsyncHandlerInterceptor> battleAsyncHandlerInterceptorList;

    @Async(value = "battleExecutor")
    public void preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        for (AsyncHandlerInterceptor battleAsyncHandlerInterceptor : battleAsyncHandlerInterceptorList) {
            try {
                battleAsyncHandlerInterceptor.preHandle(request, response, handler);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @Async(value = "battleExecutor")
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        for (AsyncHandlerInterceptor battleAsyncHandlerInterceptor : battleAsyncHandlerInterceptorList) {
            try {
                battleAsyncHandlerInterceptor.postHandle(request, response, handler, modelAndView);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    @Async(value = "battleExecutor")
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        for (AsyncHandlerInterceptor battleAsyncHandlerInterceptor : battleAsyncHandlerInterceptorList) {
            try {
                battleAsyncHandlerInterceptor.afterCompletion(request, response, handler, exception);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

}
